import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/single_chat_room.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';

part 'video_call_production.page.dart';

/// 视频通话页面
@PagePath('/video-call/:chatId')
class VideoCallProduction extends StatefulWidget {
  final String chatId;

  const VideoCallProduction({super.key, required this.chatId});

  @pageRouteQuery
  static RouteQuery query({required String chatId}) =>
      const _$VideoCallProductionQuery().call(chatId: chatId);

  @override
  State<VideoCallProduction> createState() => _VideoCallProductionState();
}

class _VideoCallProductionState extends State<VideoCallProduction>
    with SingleTickerProviderStateMixin {
  late final SingleChatRoom _singleChatRoom;
  late final UserRoom _userRoom;
  late AnimationController _breathingController;
  Timer? _autoCloseTimer;
  bool _hasEnded = false;

  @override
  void initState() {
    super.initState();
    _breathingController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);

    // 12秒后自动关闭
    _autoCloseTimer = Timer(const Duration(seconds: 12), () {
      if (mounted && !_hasEnded) {
        _endCall(false); // false表示对方未响应
      }
    });
  }

  @override
  void dispose() {
    _breathingController.dispose();
    _autoCloseTimer?.cancel();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _singleChatRoom = GlobalStateProvider.singleChatRoomOf(context);
    _userRoom = GlobalStateProvider.userRoomOf(context);
  }

  /// 结束通话
  void _endCall(bool isCancelled) {
    if (_hasEnded) return;
    _hasEnded = true;

    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) return;

    // 取消自动关闭定时器
    _autoCloseTimer?.cancel();

    // 返回上一个页面
    Navigator.of(context).pop();

    if (isCancelled) {
      // 用户主动取消
      StageWhisper.broadcast('Call cancelled by you');
    } else {
      // 对方未响应
      StageWhisper.broadcast('No response from the other party');

      // 发送拨打失败的消息
      _singleChatRoom.sendCallFailedMessage(
        widget.chatId,
        currentUser.id,
        'No response',
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final chat = _singleChatRoom.fetchSingleChatById(widget.chatId);
    final currentUser = _userRoom.fetchCurrentUser();

    if (chat == null || currentUser == null) {
      return SizedBox.shrink();
    }

    final otherUserId =
        chat.userId1 == currentUser.id ? chat.userId2 : chat.userId1;
    final otherUser = _userRoom.fetchUserById(otherUserId);

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/video-call-background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              // 对方用户头像（呼吸效果）
              Center(
                child: AnimatedBuilder(
                  animation: _breathingController,
                  builder: (context, child) {
                    return Transform.scale(
                      scale: 1.0 + (_breathingController.value * 0.1),
                      child: Container(
                        padding: EdgeInsets.all(2.w),
                        decoration: BoxDecoration(
                          color: Color(0xFFB9E8FA),
                          shape: BoxShape.circle,
                        ),
                        child: Container(
                          padding: EdgeInsets.all(2.w),
                          decoration: BoxDecoration(
                            color: Color(0xFFA9E0FD),
                            shape: BoxShape.circle,
                          ),
                          child: Container(
                            width: 85.w,
                            height: 85.w,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: Colors.white.withValues(alpha: 0.3),
                                width: 2.w,
                              ),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(42.5.r),
                              child: Image.asset(
                                otherUser?.avatar ?? AssetManifest.avatar1,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ).wrapBottom(120.h),

              // 底部挂断按钮
              Positioned(
                left: 0,
                right: 0,
                bottom: 120.h,
                child: Center(
                  child: GestureDetector(
                    onTap: () => _endCall(true),
                    child: Image.asset(
                      'assets/images/off.png',
                      width: 69.w,
                      height: 69.w,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
